package com.boot.springBoot.util.threadPool;

import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 自己动手 手撕一个线程池
 *
 * @author ysp
 * @since 2019/8/8 20:08
 */
@Slf4j
public class MyselfThreadPool {

    /**
     * 缓冲线程的队列 所有线程进入都在这里排队执行
     *  目前的线程阻塞队列有
     *      LinkedBlockingDeque<Runnable> 无界
     *     SynchronousQueue<Runnable> 0界
     *     ArrayBlockingQueue<Runnable>  有界
     *     DelayQueue  延迟阻塞队列
     *     PriorityBlockingQueue<Runnable> 优先级阻塞队列   多线程环境支持
     */


    BlockingQueue<Runnable> threadQueue;

    /**
     * 创建执行任务的工作线程
     */
    List<WorkThread> workThreads = new ArrayList<>();

    MyselfThreadPool(int poolSize,BlockingQueue<Runnable> threadQueue){
        this.threadQueue = threadQueue;
        for (int i = 0; i < poolSize; i++) {
            WorkThread workThread = new WorkThread();
            workThread.start();
            threadQueue.add(workThread);
        }
    }

    /**
     * 执行任务   实则往队列里添加任务  排队执行所有任务  以线程为单位
     */
    void execute(Runnable task) throws Exception{
        threadQueue.put(task);
    }

    //创建工作线程
    class WorkThread extends Thread{
        @Override
        public void run() {
            while (true){
                Runnable task = null;
                try {
                    task = threadQueue.take();
                }catch (Exception e){
                    log.error("线程执行发生异常：",e);
                }
                task.run();
            }
        }
    }

    public  static void main(String[] args) throws Exception{
        BlockingQueue<Runnable> threadQueue = new ArrayBlockingQueue<>(10);
        MyselfThreadPool threadPool = new MyselfThreadPool(5,threadQueue);
        for(int i = 1;i <= 20;i++){
            int num =i;
            threadPool.execute(() ->{
                    System.out.println("线程" + num + "执行:" + Thread.currentThread().getName());
            });
        }
    }
}
